package org.n.shop.service.impl;

import lombok.AllArgsConstructor;
import org.n.shop.domain.Do.SelectCommendByCommodityIdDo;
import org.n.shop.domain.Do.SelectCommodityDetailDo;
import org.n.shop.domain.entity.Comment;
import org.n.shop.domain.vo.ListVo;
import org.n.shop.mapper.CommentMapper;
import org.n.shop.result.RestResult;
import org.n.shop.result.RestResultBuilder;
import org.n.shop.service.CommentService;
import org.n.shop.util.MinioUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.n.shop.config.RedisConfig.PREFIX_USER;

@Service
@AllArgsConstructor
public class CommentServiceImpl implements CommentService {
    private CommentMapper commentMapper;
    private RedisTemplate redisTemplate;
    private MinioUtil minioUtil;

    @Override
    public RestResult all(int page, int pageSize, int commodityId) {
        List<SelectCommendByCommodityIdDo> selectCommendByCommodityIdDos = commentMapper.all(page, pageSize, commodityId);

        for (SelectCommendByCommodityIdDo selectCommendByCommodityIdDo : selectCommendByCommodityIdDos) {
            selectCommendByCommodityIdDo.setAvatar(minioUtil.getObject(selectCommendByCommodityIdDo.getAvatar()));
        }

        return new RestResultBuilder().success(
                ListVo.builder()
                        .list(selectCommendByCommodityIdDos)
                        .total(commentMapper.total(commodityId))
                        .build()
        );
    }

    @Override
    public RestResult add(String authorization, Comment comment) {
        int userId = (int) redisTemplate.opsForValue().get(PREFIX_USER + authorization);
        comment.setUserId(userId);

        if (commentMapper.add(comment) == 1) {
            return new RestResultBuilder().success();
        }
        return new RestResultBuilder().fail();
    }

    @Override
    public RestResult isCommented(int commodityId, String authorization) {
        int userId = (int) redisTemplate.opsForValue().get(PREFIX_USER + authorization);
        return new RestResultBuilder().success(
                commentMapper.isCommented(commodityId, userId)
        );
    }
}
